package action.back;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import models.Module;
import net.sf.json.JSONArray;
import net.sf.jxls.transformer.XLSTransformer;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import utils.JsonUtils;
import utils.SqlUtils;
import utils.StringHelper;
import config.Constant;

public class ModuleAction extends DefaultAction {
	
	private Module module;
	@SuppressWarnings("unchecked")
	public void sqlDrop() throws Exception{
		List<String> tables = SqlUtils.getTables("oracle");
		
		StringBuffer bf = new StringBuffer();
		for(String table :tables ){
			bf.append("drop table " + table+";</br>");
		}
		renderHtml(bf.toString());
	}
	public void sqlDelete() throws Exception{
		List<String> tables = SqlUtils.getTables("oracle");
		
		StringBuffer bf = new StringBuffer();
		for(String table :tables ){
			bf.append("delete " + table+";</br>");
		}
		
		renderHtml(bf.toString());
	}
	@SuppressWarnings("unchecked")
	public void export() throws Exception{
		
		List<Module> modules = getCommonService().findAll("from Module e where e.parent.id is null  order by e.position asc");
	    
	    Map beans = new HashMap();
	    
	    for(Module module : modules){
	    	List<Module> children = module.getChildren();
	    	
	    	for(Module child : children){
	    		List<Module> children3 = child.getChildren();
	    		for(Module child3 : children3){
		    		child3.getChildren();
		    	}
	    	}
	    }
	    beans.put("modules", modules);
	    
	    InputStream in = Constant.AppContext.getResource("classpath:modules.xls").getInputStream();
	    XLSTransformer transformer = new XLSTransformer();
	    HSSFWorkbook hsb = transformer.transformXLS(in, beans);
		response.reset();
		response.setContentType("application/vnd.ms-excel");

		response.setHeader("Content-Disposition", "attachment; filename=\"" + new String("系统模块列表.xls".getBytes(), "ISO8859-1") +"\""); 
		
		hsb.write(response.getOutputStream());
		in.close();
		in = null;
	}
	
	public String index() {
		return "index";
	}
	
	@SuppressWarnings("unchecked")
	public void getTrees() {
		Integer parent_id = Integer.parseInt(request.getParameter("parent_id"));

		List<Module> modules;
		if (parent_id == null || parent_id.intValue() == 0) {
			modules = getCommonService().findAll(Module.class, "position asc", "parent is null",null);
		} else {
			modules = getCommonService().findAll(Module.class, "position asc", "parent.id = ? ",new Object[]{parent_id});
		}

		List<Map> trees = new ArrayList<Map>();
		for (Module module : modules) {
			Map<String, Object> tree = new HashMap<String, Object>();
			tree.put("id", module.getId());
			tree.put("text", module.getName());
			tree.put("leaf", module.getSubModuleCount() + module.getSubFunctionCount() == 0 );
			if(StringHelper.parseBoolean(module.getIfFunc())){
				tree.put("iconCls", "admin-tool-func");
			}
			else{
				tree.put("iconCls", "admin-tool-module");
			}
			trees.add(tree);
		}
		
		JSONArray jsonObject = JSONArray.fromObject(trees);
		String jsonString = jsonObject.toString();
		renderJson(jsonString);
	}
	
	@SuppressWarnings("unchecked")
	public void getChildren() {
		Integer parent_id = Integer.parseInt(request.getParameter("parent_id"));
	        
	    List<Module> modules;
	    if (parent_id == null || parent_id.intValue() == 0) {
			modules = getCommonService().findAll(Module.class, "position asc", "parent is null",null);
		} else {
			modules = getCommonService().findAll(Module.class, "position asc", "parent.id = ? ",new Object[]{parent_id});
		}
	    List<Map<String, Object>> jsonList = new ArrayList<Map<String,Object>>();
	    for(Module m : modules){
	    	Map<String, Object> map = new HashMap<String, Object>();
	    	map.put("module", m);
	    	
	    	jsonList.add(map);
	    }
	    JSONArray jsonObject =  JSONArray.fromObject(jsonList,JsonUtils.configJson(new String[]{"children"}, "yyyy-MM-dd"));
		String jsonString = jsonObject.toString();
		renderJson(jsonString);
	}
	


	public void update() {
		getCommonService().update(module);
		renderJson("{success:true,id:"+module.getId()+",name:'"+module.getName()+"'}");
	}
	
	public void create() {
		
		Integer parent_id = Integer.parseInt(request.getParameter("parent_id"));
		if(parent_id>0){
			Module parent = new Module();
			parent.setId(parent_id);
			module.setParent(parent);
		}
		if(StringUtils.isEmpty(module.getCode()))
			module.setCode(StringHelper.randomCode("", 7));
		module.setIfFunc(Constant.FALSE);
		getCommonService().save(module);
		
		renderJson("{success:true,id:"+module.getId()+"}");
	}
	
	public void delete() {
		for(Integer id : ids){
			getCommonService().executeUpdate("delete RoleModule where module.id = ?", id);
			getCommonService().executeUpdate("delete Module where parent.id = ?", id);
			getCommonService().executeUpdate("delete Module where id = ?", id);
		}
		
		renderJson("{success:true}");
	}
	

	public Module getModule() {
		return module;
	}

	public void setModule(Module module) {
		this.module = module;
	}
}
